package com.ciaojian.worker.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ciaojian.core.enums.business.WorkerStatusEnum;
import com.ciaojian.core.enums.business.WorkerWorkerStatusEnum;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.vo.CheckUser;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import com.ciaojian.core.util.StringUtil;
import com.ciaojian.worker.factory.StatusModifierFactory;
import com.ciaojian.worker.model.param.DyRecordParam;
import com.ciaojian.worker.model.param.WorkerDTO;
import com.ciaojian.worker.service.DyRecordServiceImpl;
import com.ciaojian.worker.service.OrderCommissionServiceImpl;
import com.ciaojian.worker.service.WorkerServiceImpl;
import com.ciaojian.worker.strategy.workerstatus.Context;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Atlakyn
 */
@Api(tags = "发型师")
@Validated
@RestController
@RequestMapping("/workers")
public class WorkerController {
    @Resource
    private WorkerServiceImpl workerService;
    @Resource
    private DyRecordServiceImpl dyRecordService;
    @Resource
    private OrderCommissionServiceImpl orderCommissionService;

    @ApiOperation("抖音产品记录")
    @PostMapping("/douyin-record")
    public Result dyRecord(@RequestBody @Validated DyRecordParam dyRecordParam) {
        dyRecordService.dyRecord(dyRecordParam.getWorkerId(), dyRecordParam.getUserId());
        return Result.ok();
    }

    @ApiOperation("发型师取消订单")
    @GetMapping("/cancelOrder")
    public Result cancelOrder(@ApiParam(value = "订单Id", required = true) Integer id) {
        return workerService.cancelOrder(id);
    }

    /**
     * @Description: 查询发型师作品
     * @Author: xiangchao
     * @Date: 2020/12/1 12:12 下午
     */
    @ApiOperation("查询发型师作品")
    @GetMapping("findWorkerPhoto")
    public Result findWorkerPhoto(@ApiParam(value = "发型师ID", required = true) String userId) {
        return workerService.findWorkerPhoto(userId);

    }

    /**
     * @Description: 新增请假记录
     * @Author: xiangchao
     * @Date: 2020/11/9 7:17 下午
     */
    @ApiOperation("新增请假记录")
    @PostMapping("saveDCheckAskfor")
    public Result saveDCheckAskfor(@RequestBody @Valid DCheckAskfor data) throws Exception {
        return workerService.saveDCheckAskfor(data);
    }

    @ApiOperation("新增发型师作品")
    @PostMapping("saveDWorkerPhoto")
    public Result saveDWorkerPhoto(@RequestBody WorkerPhoto data) {
        return workerService.saveDWorkerPhoto(data);
    }

    @ApiOperation("查询本月还剩几次补卡")
    @GetMapping("thisMonthCount")
    public Result thisMonthCount(@ApiParam("发型师ID") String id) {
        return workerService.thisMonthCount(id);
    }


    /**
     * @Description: 查询考勤汇总
     * @Author: xiangchao
     * @Date: 2020/11/11 11:26 上午
     */
    @ApiOperation("查询考勤汇总")
    @GetMapping("getAttendanceSummary")
    public Result getAttendanceSummary(@ApiParam(value = "月份:YYYY-mm", required = true) String date,
                                       @ApiParam(value = "发型师ID", required = true) String id) {
        return workerService.getAttendanceSummary(date, id);
    }

    @ApiOperation("查询每日考勤记录")
    @GetMapping("findAttendanceList")
    public Result findAttendanceList(@ApiParam(value = "月份:YYYY-mm", required = true) String date,
                                     @ApiParam(value = "发型师ID", required = true) String id) {
        String thisMonth = new SimpleDateFormat("yyyy-MM").format(new Date());
        // 如果一样说明是本月
        if (thisMonth.equals(date)) {
            List<String> dates = StringUtil.getDates(date + "-01", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            return Result.ok(dates);
        }
        // 循环全部日期
        if (thisMonth.compareTo(date) > -1) {
            String lastDate = workerService.getBaseMapper().getLastDate(date + "-01");
            List<String> dates = StringUtil.getDates(date + "-01", lastDate);
            return Result.ok(dates);
        } else {    // 未来日期
            return Result.ok();
        }
    }

    @ApiOperation("新增打卡记录")
    @PostMapping("saveDCheckUser")
    public Result saveCheckUser(@RequestBody @Valid CheckUser data) {
        return workerService.saveDCheckUser(data);
    }

    @ApiOperation("修改订单状态")
    @PostMapping("updateOrderStatus")
    public Result updateOrderStatus(@RequestBody Order data) {
        Integer orderStatus = workerService.getBaseMapper().getOrderStatus(data.getId());
        if (orderStatus == -1) {
            return Result.error("用户已取消该订单");
        }
        return workerService.updateOrderStatus(data);
    }

    /**
     * @Description: 查询头部统计
     * @Author: xiangchao
     * @Date: 2020/11/9 1:03 下午
     */
    @ApiOperation("查询头部统计")
    @GetMapping("getDHeaderCount")
    public Result getDHeaderCount(@NotNull(message = "发型师Id不能为空") @ApiParam("发型师ID") String id) {
        try {
            return workerService.getDHeaderCount(id);
        } catch (Exception e) {
            LogUtil.writeErrorLog(e.toString());
            return Result.error("失败");
        }
    }

    @ApiOperation("获取发型师状态")
    @GetMapping("getWorkerStatus")
    public Result getWorkerStatus(Integer id) {
        try {
            QueryWrapper<Worker> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            queryWrapper.select("worker_status");
            Worker worker = workerService.getOne(queryWrapper);
            HashMap<String, Object> map = new HashMap<>(1);
            map.put("status", worker.getWorkerStatus());
            return Result.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.writeErrorLog(e.toString());
            return Result.error("失败");
        }
    }

    @ApiOperation("根据Id查询发型师信息")
    @GetMapping("/{workerId}")
    public Result getWorker(@PathVariable Integer workerId) {
        return Result.ok(workerService.getBaseMapper().selectWorkerDTO(workerId));
    }


    @ApiOperation("查询上下班时间")
    @PostMapping("/getStartEndWorkTime")
    public Result getStartEndWorkTime(@RequestBody @Valid DCheckUserTime data) {
        try {
            return workerService.getStartEndWorkTime(data);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.writeErrorLog(e.toString());
            return Result.error("系统错误!");
        }
    }


    @ApiOperation(value = "门店下全部发型师", response = Worker.class)
    @GetMapping("/store/{storeId}")
    public Result getByStoreId(@PathVariable Integer storeId) {
        LambdaQueryWrapper<Worker> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Worker::getStoreId, storeId)
                .ne(Worker::getStatus, WorkerStatusEnum.outgoing);
        return Result.ok(new Worker().selectList(lambdaQueryWrapper));
    }

    @ApiOperation("查询发型师")
    @GetMapping("/list")
    public Result list(WorkerDTO dto) {
        List<Worker> list = workerService.lambdaQuery()
                .eq(Worker::getMotor, dto.getMotor())
                .ne(Worker::getStatus,WorkerStatusEnum.outgoing)
                .list();
        return Result.ok(list);
    }

    @ApiOperation("修改发型师状态")
    @GetMapping("/change/worker-status")
    public Result changeWorkerStatus(@ApiParam Integer workerId,
                                     @ApiParam WorkerWorkerStatusEnum workerStatus) {
        Context context = new Context(StatusModifierFactory.get(workerStatus));
        Worker worker = new Worker().selectById(workerId);
        context.handle(worker);
        return Result.ok();
    }

    @ApiOperation("/修改发型师端信息")
    @PutMapping({"/update"})
    public Result update(@RequestBody List<WorkerDTO> list) {
        List<Worker> workerList = new ArrayList<>();
        list.forEach(workerDTO -> workerList.add(workerDTO.convert()));
        return Result.save(this.workerService.updateBatchById(workerList));
    }

    /**
     * @Description: 修改发型师状态
     * @Author: xiangchao
     * @Date: 2020/11/13 2:18 下午
     */
    @ApiOperation("修改发型师状态 过期不再维护")
    @GetMapping("edidWorkerStatus")
    public Result edidWorkerStatus(@ApiParam(value = "发型师ID", required = true) Integer id,
                                   @ApiParam(value = "状态: 0上班 1就餐 11轻餐 2下班", required = true) Integer status) {
        Worker worker = new Worker().selectById(id);
        Assert.notNull(worker, "发型师不存在");
        try {
            new Oplog()
                    .setTelphone(worker.getTelphone())
                    .setAccount(worker.getName())
                    .setWorkerId(worker.getId())
                    .setModular("发型师修改状态")
                    .setContent("发型师修改状态为" + status)
                    .insert();

            // 发型师干饭
            if (status == 1) {
                return Result.save(workerService.dinner(worker));
            }
            // 发型师吃下午茶
            else if (status == 11) {
                return Result.save(workerService.afternoonTea(worker));
            } else {
                UpdateWrapper updateWrapper = new UpdateWrapper();
                updateWrapper.set("worker_status", status);
                updateWrapper.eq("id", id);
                workerService.update(updateWrapper);
                return Result.ok();
            }
        } catch (Exception e) {
            LogUtil.writeErrorLog(e.toString());
            return Result.error("修改失败");
        }
    }

    @ApiOperation("/员工提成查看")
    @GetMapping("/salary")
    public Result salary(@RequestParam Integer workerId,
                         @DateTimeFormat(pattern = "yyyy-MM") Date month) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(month);
            calendar.add(Calendar.MONTH, +1);
            calendar.add(Calendar.MINUTE, -1);
            Date endTime = calendar.getTime();


        return Result.ok( orderCommissionService.getsalary(workerId,month,endTime));
    }
}
